package com.link.play.fit.ai.ui.vip

import android.annotation.SuppressLint
import android.graphics.Paint
import android.os.Bundle
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.android.billingclient.api.ProductDetails
import com.link.play.fit.ai.R
import com.link.play.fit.ai.RemoteConfig.daysCaloriePlan
import com.link.play.fit.ai.RemoteConfig.vipProductCaloriePlan
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.bean.UserGuide
import com.link.play.fit.ai.databinding.VipPlanAcLayoutBinding
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.kv.AuthCache.FIRBASE_SUB_PRODUCT_ID
import com.link.play.fit.ai.kv.AuthCache.SUB_CURRENCY
import com.link.play.fit.ai.kv.AuthCache.SUB_PRICE_VALUE
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_USER_GUIDE
import com.link.play.fit.ai.utils.CalendarUtils.calculateEndByStartDate
import com.link.play.fit.ai.utils.DateEx.getCurrentDayOfMonth
import com.link.play.fit.ai.utils.GooglePayUtil
import com.link.play.fit.ai.utils.GooglePayUtil.defaultAppPlanPrice
import com.link.play.fit.ai.utils.GooglePayUtil.extractAndCalculateDailyPriceToPlanDays
import com.link.play.fit.ai.utils.GooglePayUtil.extractAndCalculateDailyPriceToPlanDaysx2
import com.link.play.fit.ai.utils.GooglePayUtil.google_pay_id
import com.link.play.fit.ai.utils.GooglePayUtil.parsePriceString
import com.link.play.fit.ai.utils.OpenAgreementUtils
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class VipPlanAc : BaseActivity<VipPlanAcLayoutBinding>(VipPlanAcLayoutBinding::inflate) {
    private var product: ProductDetails? = null
    private var type = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        type = intent.extras?.getString("buyType").toString()
        "type  $type".d()

        EventBus.getDefault().register(this)
        initData()
        initListener()
        queryProductDetails()
        google_pay_id = vipProductCaloriePlan
        binding.priceText2.paintFlags = binding.priceText2.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
        //EventUtils.event("vip_plan_ac", value = "page")
    }

    private fun initData() = with(binding) {
        priceText.text = getString(
            R.string.price_day,
            extractAndCalculateDailyPriceToPlanDays(defaultAppPlanPrice, daysCaloriePlan)
        )
        priceText2.text = getString(
            R.string.price_day,
            extractAndCalculateDailyPriceToPlanDaysx2(defaultAppPlanPrice, daysCaloriePlan)
        )


        termsText.paintFlags = termsText.paintFlags or Paint.UNDERLINE_TEXT_FLAG
        privacyText.paintFlags = privacyText.paintFlags or Paint.UNDERLINE_TEXT_FLAG
        RestoreText.paintFlags = RestoreText.paintFlags or Paint.UNDERLINE_TEXT_FLAG

    }

    private fun initListener() = with(binding) {
        backImg.setOnClickListener {
            finish()
        }
        continueText.setOnClickListener {
            product?.let {
                FIRBASE_SUB_PRODUCT_ID = it.productId
                SUB_PRICE_VALUE =
                    parsePriceString(it.oneTimePurchaseOfferDetails?.formattedPrice ?: "0.0")
                SUB_CURRENCY = it.oneTimePurchaseOfferDetails?.priceCurrencyCode.orEmpty()
                GooglePayUtil.launchPurchaseFlow(this@VipPlanAc, productDetails = it)
            }
        }
        termsText.setOnClickListener {
            OpenAgreementUtils.openTerms(this@VipPlanAc)
        }
        privacyText.setOnClickListener {
            OpenAgreementUtils.openPrivacy(this@VipPlanAc)
        }
        RestoreText.setOnClickListener {
            product?.let {
                GooglePayUtil.launchPurchaseFlow(this@VipPlanAc, productDetails = it)
            }
        }
        subLayout.setOnClickListener {
            product?.let {
                GooglePayUtil.launchPurchaseFlow(this@VipPlanAc, productDetails = it)
            }
        }
    }

    private fun queryProductDetails() = with(binding) {
        // 查询商品
        lifecycleScope.launch {
            product = GooglePayUtil.queryProduct(vipProductCaloriePlan, false)
            product?.let {
                // 显示商品信息
                "formattedPrice  ${it.oneTimePurchaseOfferDetails?.formattedPrice}".d()
                "name  ${it.name}".d()
                "productId  ${it.productId}".d()
                "priceAmountMicros  ${it.oneTimePurchaseOfferDetails?.priceAmountMicros}".d()
                "priceCurrencyCode  ${it.oneTimePurchaseOfferDetails?.priceCurrencyCode}".d()
                it.oneTimePurchaseOfferDetails?.formattedPrice?.let { k ->
                    priceText.text = getString(
                        R.string.price_day,
                        extractAndCalculateDailyPriceToPlanDays(k, daysCaloriePlan)
                    )
                    priceText2.text = getString(
                        R.string.price_day,
                        extractAndCalculateDailyPriceToPlanDaysx2(k, daysCaloriePlan)
                    )
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: String) {
        if (event == "isAppPurchaseVip") {
            Toast.makeText(this, getString(R.string.Purchase_successful), Toast.LENGTH_SHORT)
                .show()
            lifecycleScope.launch {
                val userGuide = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
                userGuide?.apply {
                    isAppPurchaseVip = true
                    if(planProductEndTime.isEmpty()){
                        planStartTime = getCurrentDayOfMonth()
                    }
                    planProductEndTime = if(planProductEndTime.isEmpty()){
                        calculateEndByStartDate(getCurrentDayOfMonth(),daysCaloriePlan.toLong())
                    }else{
                        calculateEndByStartDate(planProductEndTime,daysCaloriePlan.toLong())
                    }
                    CloudStore.set(DOC_USER_GUIDE,this)

                    "type  $type".d()
                    if(type == "controlPlan"){
                        EventBus.getDefault().post("flushResult")
                    }else if(type == "controlFg"){
                        EventBus.getDefault().post("flushMain")
                    }
                }


                finish()
            }

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

}